package com.sgb.kjwl.view.ui.activity.self.publish;

import static com.swgk.core.event.EventConstant.EVENT_SELECT_ARR;
import static com.swgk.core.event.EventConstant.EVENT_SPEC_PRICE;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGoodsSpecBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.GetSkuEntity1;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.kjwl.view.event.self.GoodsSkuEvent;
import com.sgb.kjwl.view.ui.adapter.self.publish.GoodsSpecAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.SpecPriceAdapter;
import com.sgb.kjwl.viewmodel.self.publish.GoodsSpecModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.view.entity.GoodsPublishSkuListEntity;
import com.swgk.core.view.entity.GoodsSkuChild1;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;


public class GoodsSpecActivity extends AppActivity {


    ActivityGoodsSpecBinding binding;
    private GoodsSpecAdapter goodsSpecAdapter;
    private SpecPriceAdapter specPriceAdapter;
    @Inject
    GoodsSpecModel viewModel;
    private HashSet<String> checkFlagList = new HashSet<>();
    private List<GetSkuEntity1> skuEntities;
    private List<GoodsPublishSkuListEntity> combinationData;
    private List<GoodsPublishSkuListEntity> combinationSet;
    private List<GoodsPublishSkuListEntity> combinationOld;
    //被选中的集合
    private List<List<GoodsSkuChild1>> aggregate;
    private String cid3;
    private String id = "";

    private List<GoodsPublishSkuListEntity> selectList;


    public static void start(Context context, String cid3, String id) {
        Intent intent = new Intent();
        intent.putExtra("cid3", cid3);
        intent.putExtra("id", id);
        intent.setClass(context, GoodsSpecActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_goods_spec);
        cid3 = getIntent().getStringExtra("cid3");
        id = getIntent().getStringExtra("id");
        binding.include.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.include.titleView.setText("商品规格");
        binding.tvPl.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);

        goodsSpecAdapter = new GoodsSpecAdapter(getActivity(), null);
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getActivity());
        binding.rvCheck.setAdapter(goodsSpecAdapter);
        binding.rvCheck.setLayoutManager(gridLayoutManager);
        goodsSpecAdapter.onItemChildCLickListener(new GoodsSpecAdapter.ItemChildCLickListener() {
            @Override
            public void checkArr(Map<Integer, Set<Integer>> map, int position) {
                int allSize = 1;
                GoodsPublishSkuListEntity addData = null;
                combinationData.clear();
                aggregate.clear();
                // 获取键集合的迭代器
                Iterator it = map.keySet().iterator();
                while (it.hasNext()) {
                    int next = (int) it.next();
                    if (map.get(next).size() != 0) {
                        allSize = map.get(next).size() * allSize;
                        setArrItem(map.get(next), next);
                    }
                }
                for (int i = 0; i < allSize; i++) {
                    addData = new GoodsPublishSkuListEntity();
                    combinationData.add(addData);
                }
                selectList.clear();
                getSelectList(aggregate, aggregate.get(0), new ArrayList<GoodsSkuChild1>());
                for (int j = 0; j < combinationData.size(); j++) {
                    combinationData.get(j).setList(selectList.get(j).getList());
                }
                specPriceAdapter.setDatas(combinationData);
            }

            @Override
            public void addDefaultPriceData() {
                GoodsPublishSkuListEntity addData = new GoodsPublishSkuListEntity();
                addData.setFill(true);
                combinationData.add(addData);
                specPriceAdapter.setDatas(combinationData);
            }

            @Override
            public void deleteAll() {
                combinationData.clear();
                specPriceAdapter.setDatas(combinationData);
            }
        });
        LinearLayoutManager gridLayoutManager2 = new LinearLayoutManager(getActivity());
        specPriceAdapter = new SpecPriceAdapter(getActivity(), null);
        binding.rvPl.setAdapter(specPriceAdapter);
        binding.rvPl.setLayoutManager(gridLayoutManager2);
    }

    @Override
    protected void init() {
        super.init();
        selectList = new ArrayList<>();
        combinationData = new ArrayList<>();
        combinationSet = new ArrayList<>();
        combinationOld = new ArrayList<>();
        aggregate = new ArrayList<>();
        viewModel.getSku(cid3);
    }

    public void isSku(List<GetSkuEntity1> data) {
        skuEntities = data;
        if (data != null && data.size() != 0) {
            //循环设置全部不选中
            for (int i = 0; i < data.size(); i++) {
                data.get(i).setIsSelect("1");
                for (int j = 0; j < data.get(i).getList().size(); j++) {
                    data.get(i).getList().get(j).setOnClick(false);
                }
            }
            //循环设置已选中
            for (String valId : checkFlagList) {
                for (int i = 0; i < data.size(); i++) {
                    for (int j = 0; j < data.get(i).getList().size(); j++) {
                        if (valId.equals(data.get(i).getList().get(j).getValId())) {
                            data.get(i).getList().get(j).setOnClick(true);
                            data.get(i).setIsSelect("0");
                        }
                    }
                }
            }
            goodsSpecAdapter.setDatas(data);
            String isFill = skuIsFill(data);
            if ("".equals(isFill) && checkFlagList.size() == 0) {
                GoodsPublishSkuListEntity addData = new GoodsPublishSkuListEntity();
                if (combinationSet != null && combinationSet.size() == 1) {
                    if (combinationSet.get(0).getList() == null || combinationSet.get(0).getList().size() == 0) {
                        addData.setMoney(combinationSet.get(0).getMoney());
                    }
                }
                combinationData.clear();
                addData.setFill(true);
                combinationData.add(addData);
                specPriceAdapter.setDatas(combinationData);
            } else {
                specPriceAdapter.setDatas(combinationSet);
            }
        }
    }

    private String skuIsFill(List<GetSkuEntity1> data) {
        for (int i = 0; i < data.size(); i++) {
            if ("1".equals(data.get(i).getIsFill())) {
                if (!isHaveClick(data.get(i).getList())) {
                    return data.get(i).getParamData();
                }
            }
        }
        return "";
    }


    private boolean isHaveClick(List<GoodsSkuChild1> itemData) {
        for (int i = 0; i < itemData.size(); i++) {
            if (itemData.get(i).isOnClick()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_pl:
                if (specPriceAdapter.getDatas().size() != 0) {
                    showETextDialog();
                } else {
                    MToast.showToast(GoodsSpecActivity.this, "请先选择规格");
                }
                break;
            case R.id.next_view:
                if (specPriceAdapter.getDatas().size() != 0) {
                    if (!"".equals(skuIsFill(goodsSpecAdapter.getDatas()))) {
                        MToast.showToast(GoodsSpecActivity.this, "请勾选商品规格");
                        return;
                    }
                    List<GoodsPublishSkuListEntity> newList = specPriceAdapter.getDatas();
                    if (isFillMoney(newList)) {
                        List<GoodsPublishSkuListEntity> oldList = combinationOld;
                        if (oldList != null) {
                            for (int h = 0; h < newList.size(); h++) {
                                for (int j = 0; j < oldList.size(); j++) {
                                    GoodsPublishSkuListEntity oldEntity = oldList.get(j);
                                    GoodsPublishSkuListEntity newEntity = newList.get(h);
                                    StringBuffer oldString = new StringBuffer();
                                    StringBuffer newString = new StringBuffer();
                                    for (int a = 0; a < oldEntity.getList().size(); a++) {
                                        oldString.append(oldEntity.getList().get(a).getValId());
                                    }
                                    for (int b = 0; b < newEntity.getList().size(); b++) {
                                        newString.append(newEntity.getList().get(b).getValId());
                                    }
                                    if (oldString.toString().equals(newString.toString())) {
                                        newEntity.setId(oldEntity.getId());
                                        newEntity.setVipMaxPrice(oldEntity.getVipMaxPrice());
                                    }
                                }
                            }
                        }
                        if (isRightPrice(newList)) {
                            GoodsEvent goodsEvent = new GoodsEvent();
                            goodsEvent.setMessageTag(EVENT_SPEC_PRICE);
                            goodsEvent.setObject(newList);
                            EventBus.getDefault().post(goodsEvent);
                            finish();
                        }
                    }
                } else {
                    MToast.showToast(GoodsSpecActivity.this, "请先选择规格");
                }
                break;
            default:
                break;
        }
    }

    private boolean isRightPrice(List<GoodsPublishSkuListEntity> newList) {
        for (int i = 0; i < newList.size(); i++) {
            if (!TextUtils.isEmpty(newList.get(i).getMoney()) && !TextUtils.isEmpty(newList.get(i).getVipMaxPrice())) {
                BigDecimal money = new BigDecimal(newList.get(i).getMoney());
                BigDecimal vipMaxPrice = new BigDecimal(newList.get(i).getVipMaxPrice());
                if (money.compareTo(vipMaxPrice) == -1) {
                    //销售价小于会员价
                    MToast.showToast(GoodsSpecActivity.this, "销售价不能低于会员价");
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isFillMoney(List<GoodsPublishSkuListEntity> newList) {
        for (int i = 0; i < newList.size(); i++) {
            if (newList.get(i).getMoney() == null || "".equals(newList.get(i).getMoney())) {
                MToast.showToast(GoodsSpecActivity.this, "请填写完整单价");
                return false;
            }
        }
        return true;
    }

    //取出所有选中的值
    private void setArrItem(Set<Integer> set, int position) {
        List<GoodsSkuChild1> select = new ArrayList<>();
        for (int i = 0; i < skuEntities.size(); i++) {
            if (position == i) {
                Iterator it = set.iterator();
                while (it.hasNext()) {
                    select.add(skuEntities.get(position).getList().get((Integer) it.next()));
                }
                aggregate.add(select);
            }
        }
    }

    List<GoodsSkuChild1> arr2 = new ArrayList<>();

    public void getSelectList(List<List<GoodsSkuChild1>> list, List<GoodsSkuChild1> arr, List<GoodsSkuChild1> str) {
        for (int i = 0; i < list.size(); i++) {
            //取得当前的数组bai
            if (i == list.indexOf(arr)) {
                //迭代du数组
                for (GoodsSkuChild1 st : arr) {
                    arr2.clear();
                    List<GoodsSkuChild1> temp = new ArrayList<>();
                    temp.add(st);
                    temp.addAll(str);
                    arr2.addAll(temp);
                    if (i < list.size() - 1) {
                        getSelectList(list, list.get(i + 1), temp);
                    } else if (i == list.size() - 1) {
                        GoodsPublishSkuListEntity goodsPublishSkuListEntity = new GoodsPublishSkuListEntity();
                        for (int k = 0; k < arr2.size(); k++) {
                            goodsPublishSkuListEntity.getList().add(arr2.get(k));
                        }
                        selectList.add(goodsPublishSkuListEntity);
                    }
                }
            }
        }
    }

    private void showETextDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_text_btn2, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        EditText et_content = view.findViewById(R.id.et_content);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (combinationData.size() != 0) {
                    for (int i = 0; i < combinationData.size(); i++) {
                        combinationData.get(i).setMoney(et_content.getText().toString());
                    }
                }
                specPriceAdapter.setDatas(combinationData);
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGoodsSkuEvent(GoodsSkuEvent event) {
        if (event.getMessageTag() == EVENT_SELECT_ARR) {
            combinationSet = (List<GoodsPublishSkuListEntity>) event.getObject();
            combinationOld = (List<GoodsPublishSkuListEntity>) event.getMessageData();
            getCheckFlagListById();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    public HashSet<String> getCheckFlagListById() {
        checkFlagList.clear();
        for (int i = 0; i < combinationSet.size(); i++) {
            for (int j = 0; j < combinationSet.get(i).getList().size(); j++) {
                checkFlagList.add(combinationSet.get(i).getList().get(j).getValId());
            }
        }
        return checkFlagList;
    }

}